<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vision Analyzer - LLM配置</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
            color: #333;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            border-radius: 12px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
            font-weight: 700;
        }

        .header p {
            font-size: 1.1rem;
            opacity: 0.9;
        }

        .content {
            padding: 40px;
        }

        .provider-tabs {
            display: flex;
            gap: 10px;
            margin-bottom: 30px;
            border-bottom: 2px solid #e0e0e0;
        }

        .tab {
            padding: 12px 24px;
            background: none;
            border: none;
            cursor: pointer;
            font-size: 1rem;
            font-weight: 500;
            color: #666;
            transition: all 0.3s ease;
            border-bottom: 3px solid transparent;
        }

        .tab.active {
            color: #4facfe;
            border-bottom-color: #4facfe;
        }

        .tab:hover {
            color: #4facfe;
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
        }

        .form-group {
            margin-bottom: 25px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #444;
        }

        .form-group input, .form-group select {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 1rem;
            transition: border-color 0.3s ease;
        }

        .password-input-container {
            position: relative;
            display: flex;
            align-items: center;
        }

        .password-input-container input {
            padding-right: 45px;
        }

        .password-toggle {
            position: absolute;
            right: 12px;
            cursor: pointer;
            user-select: none;
            color: #666;
            font-size: 18px;
            background: none;
            border: none;
            padding: 5px;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: color 0.3s ease;
        }

        .password-toggle:hover {
            color: #4facfe;
        }

        .password-toggle:active {
            color: #2196F3;
        }

        .form-group input:focus, .form-group select:focus {
            outline: none;
            border-color: #4facfe;
        }

        .btn {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            border: none;
            padding: 14px 28px;
            border-radius: 8px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-right: 10px;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(79, 172, 254, 0.3);
        }

        .btn-secondary {
            background: #e0e0e0;
            color: #666;
        }

        .btn-secondary:hover {
            background: #d0d0d0;
        }

        .btn-primary {
            background: #4CAF50;
            color: white;
        }

        .btn-primary:hover {
            background: #45a049;
        }

        .provider-info {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 25px;
        }

        .provider-info h3 {
            color: #4facfe;
            margin-bottom: 10px;
        }

        .provider-info p {
            line-height: 1.6;
            color: #666;
        }

        .alert {
            padding: 15px 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            display: none;
        }

        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .alert-info {
            background: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }

        .loading {
            display: none;
            text-align: center;
            margin: 20px 0;
        }

        .spinner {
            border: 3px solid #f3f3f3;
            border-top: 3px solid #4facfe;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 10px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .footer {
            background: #f8f9fa;
            padding: 20px 40px;
            text-align: center;
            color: #666;
            border-top: 1px solid #e0e0e0;
        }

        .btn-group {
            margin-top: 30px;
            text-align: center;
        }
    </style>
    <script>
        // 页面加载前定义全局函数，确保内联事件处理器可以访问
        window.showPassword = function(inputId) {
            const input = document.getElementById(inputId);
            if (input) {
                input.type = 'text';
            }
        };

        window.hidePassword = function(inputId) {
            const input = document.getElementById(inputId);
            if (input) {
                input.type = 'password';
            }
        };
    </script>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🎯 Vision Analyzer</h1>
            <p>配置您的LLM服务提供商以启用视觉分析功能</p>
            <p style="margin-top: 10px; font-size: 0.9rem;">
                <a href="/manage" style="color: white; text-decoration: underline;">🔧 进入管理界面</a>
            </p>
        </div>

        <div class="content">
            <div class="alert alert-info" id="infoAlert">
                <strong>提示：</strong>请至少配置一个有效的LLM服务提供商
            </div>

            <div class="alert alert-success" id="successAlert">
                <strong>成功！</strong>配置已保存
            </div>

            <div class="alert alert-error" id="errorAlert">
                <strong>错误：</strong><span id="errorMessage"></span>
            </div>

            <div class="provider-tabs">
                <button class="tab active" onclick="showTab('zai')">智谱AI (Zai)</button>
                <button class="tab" onclick="showTab('moonshot')">Moonshot</button>
                <button class="tab" onclick="showTab('tencent')">腾讯混元</button>
                <button class="tab" onclick="showTab('custom')">自定义</button>
            </div>

            <!-- Zai (智谱AI) -->
            <div id="zai" class="tab-content active">
                <div class="provider-info">
                    <h3>🧠 智谱AI (Zai)</h3>
                    <p><strong>模型：</strong>glm-4.5v (视觉理解)</p>
                    <p><strong>注册地址：</strong><a href="https://open.bigmodel.cn/" target="_blank">https://open.bigmodel.cn/</a></p>
                    <p><strong>说明：</strong>智谱AI提供高质量的中文视觉理解能力，适合中文用户使用</p>
                </div>

                <form id="zaiForm">
                    <div class="form-group">
                        <label for="zaiApiKey">API密钥</label>
                        <div class="password-input-container">
                            <input type="password" id="zaiApiKey" placeholder="请输入您的智谱AI API密钥" value="{{zaiApiKey}}" required>
                            <button class="password-toggle" onmousedown="event.preventDefault(); showPassword('zaiApiKey')" onmouseup="event.preventDefault(); hidePassword('zaiApiKey')" onmouseleave="event.preventDefault(); hidePassword('zaiApiKey')" ontouchstart="event.preventDefault(); showPassword('zaiApiKey')" ontouchend="event.preventDefault(); hidePassword('zaiApiKey')" title="按住显示密码" type="button">
                                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                    <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
                                    <circle cx="12" cy="12" r="3"></circle>
                                </svg>
                            </button>
                        </div>
                    </div>
                </form>
            </div>

            <!-- Moonshot -->
            <div id="moonshot" class="tab-content">
                <div class="provider-info">
                    <h3>🌙 Moonshot AI</h3>
                    <p><strong>模型：</strong>moonshot-v1-128k-vision-preview, moonshot-v1-32k-vision-preview, moonshot-v1-8k-vision-preview</p>
                    <p><strong>注册地址：</strong><a href="https://platform.moonshot.cn/" target="_blank">https://platform.moonshot.cn/</a></p>
                    <p><strong>说明：</strong>月之暗面提供的多模态大模型，支持高分辨率图像理解</p>
                </div>

                <form id="moonshotForm">
                    <div class="form-group">
                        <label for="moonshotApiKey">API密钥</label>
                        <div class="password-input-container">
                            <input type="password" id="moonshotApiKey" placeholder="请输入您的Moonshot API密钥" value="{{moonshotApiKey}}" required>
                            <button class="password-toggle" onmousedown="event.preventDefault(); showPassword('moonshotApiKey')" onmouseup="event.preventDefault(); hidePassword('moonshotApiKey')" onmouseleave="event.preventDefault(); hidePassword('moonshotApiKey')" ontouchstart="event.preventDefault(); showPassword('moonshotApiKey')" ontouchend="event.preventDefault(); hidePassword('moonshotApiKey')" title="按住显示密码" type="button">
                                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                    <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
                                    <circle cx="12" cy="12" r="3"></circle>
                                </svg>
                            </button>
                        </div>
                    </div>
                </form>
            </div>

            <!-- Tencent -->
            <div id="tencent" class="tab-content">
                <div class="provider-info">
                    <h3>🏢 腾讯混元</h3>
                    <p><strong>模型：</strong>hunyuan-t1-vision, hunyuan-vision, hunyuan-turbo-vision</p>
                    <p><strong>注册地址：</strong><a href="https://console.cloud.tencent.com/hunyuan" target="_blank">https://console.cloud.tencent.com/hunyuan</a></p>
                    <p><strong>说明：</strong>腾讯提供的混元大模型，性能优异，支持多种视觉任务</p>
                </div>

                <form id="tencentForm">
                    <div class="form-group">
                        <label for="tencentApiKey">API密钥</label>
                        <div class="password-input-container">
                            <input type="password" id="tencentApiKey" placeholder="请输入您的腾讯混元 API密钥" value="{{tencentApiKey}}" required>
                            <button class="password-toggle" onmousedown="event.preventDefault(); showPassword('tencentApiKey')" onmouseup="event.preventDefault(); hidePassword('tencentApiKey')" onmouseleave="event.preventDefault(); hidePassword('tencentApiKey')" ontouchstart="event.preventDefault(); showPassword('tencentApiKey')" ontouchend="event.preventDefault(); hidePassword('tencentApiKey')" title="按住显示密码" type="button">
                                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                    <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
                                    <circle cx="12" cy="12" r="3"></circle>
                                </svg>
                            </button>
                        </div>
                    </div>
                </form>
            </div>

            <!-- Custom -->
            <div id="custom" class="tab-content">
                <div class="provider-info">
                    <h3>🔧 自定义服务商</h3>
                    <p><strong>说明：</strong>如果您有其他兼容OpenAI API格式的服务商，可以在这里配置</p>
                </div>

                <form id="customForm">
                    <div class="form-group">
                        <label for="customName">服务商名称</label>
                        <input type="text" id="customName" placeholder="例如: openai, claude" value="{{customName}}" required>
                    </div>

                    <div class="form-group">
                        <label for="customBaseUrl">API基础URL</label>
                        <input type="url" id="customBaseUrl" placeholder="https://api.openai.com/v1" value="{{customBaseUrl}}" required>
                    </div>

                    <div class="form-group">
                        <label for="customApiKey">API密钥</label>
                        <div class="password-input-container">
                            <input type="password" id="customApiKey" placeholder="请输入您的API密钥" value="{{customApiKey}}" required>
                            <button class="password-toggle" onmousedown="event.preventDefault(); showPassword('customApiKey')" onmouseup="event.preventDefault(); hidePassword('customApiKey')" onmouseleave="event.preventDefault(); hidePassword('customApiKey')" ontouchstart="event.preventDefault(); showPassword('customApiKey')" ontouchend="event.preventDefault(); hidePassword('customApiKey')" title="按住显示密码" type="button">
                                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                    <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
                                    <circle cx="12" cy="12" r="3"></circle>
                                </svg>
                            </button>
                        </div>
                    </div>
                </form>
            </div>

            <div class="loading" id="loading">
                <div class="spinner"></div>
                <p>正在验证API密钥...</p>
            </div>

            <div class="btn-group">
                <button class="btn" onclick="validateAndSaveCurrentProvider()">验证并保存</button>
            </div>
        </div>

        <div class="footer">
            <p>配置完成后，请保存配置并重新启动Vision Analyzer以使用完整的视觉分析功能</p>
        </div>
    </div>

    <script>
        let currentTab = 'zai';

        // 显示密码
        function showPassword(inputId) {
            const input = document.getElementById(inputId);
            if (input) {
                input.type = 'text';
            }
        }

        // 隐藏密码
        function hidePassword(inputId) {
            const input = document.getElementById(inputId);
            if (input) {
                input.type = 'password';
            }
        }

        function showTab(tabName) {
            // 隐藏所有tab内容
            const contents = document.querySelectorAll('.tab-content');
            contents.forEach(content => content.classList.remove('active'));

            // 移除所有tab的active类
            const tabs = document.querySelectorAll('.tab');
            tabs.forEach(tab => tab.classList.remove('active'));

            // 显示选中的tab
            document.getElementById(tabName).classList.add('active');
            event.target.classList.add('active');

            currentTab = tabName;

            // 隐藏所有提示信息
            hideAllAlerts();
        }

        function hideAllAlerts() {
            document.getElementById('infoAlert').style.display = 'none';
            document.getElementById('successAlert').style.display = 'none';
            document.getElementById('errorAlert').style.display = 'none';
        }

        function showAlert(type, message) {
            hideAllAlerts();
            const alert = document.getElementById(type + 'Alert');
            if (type === 'error' && message) {
                document.getElementById('errorMessage').textContent = message;
            }
            alert.style.display = 'block';
        }

        function showLoading(show) {
            document.getElementById('loading').style.display = show ? 'block' : 'none';
        }

        function getCurrentProviderData() {
            let data = {};

            switch (currentTab) {
                case 'zai':
                    data = {
                        name: 'zai',
                        baseUrl: 'https://open.bigmodel.cn/api/paas/v4',
                        apiKey: document.getElementById('zaiApiKey').value.trim()
                    };
                    break;
                case 'moonshot':
                    data = {
                        name: 'moonshot',
                        baseUrl: 'https://api.moonshot.cn/v1',
                        apiKey: document.getElementById('moonshotApiKey').value.trim()
                    };
                    break;
                case 'tencent':
                    data = {
                        name: 'tencent',
                        baseUrl: 'https://api.hunyuan.cloud.tencent.com/v1',
                        apiKey: document.getElementById('tencentApiKey').value.trim()
                    };
                    break;
                case 'custom':
                    data = {
                        name: document.getElementById('customName').value.trim(),
                        baseUrl: document.getElementById('customBaseUrl').value.trim(),
                        apiKey: document.getElementById('customApiKey').value.trim()
                    };
                    break;
            }

            return data;
        }

        async function validateAndSaveCurrentProvider() {
            const data = getCurrentProviderData();

            if (!data.apiKey) {
                showAlert('error', '请输入API密钥');
                return;
            }

            // 检查API密钥是否为占位符或示例文本
            const placeholderPatterns = [
                /your-.*-api-key-here/i,
                /你的.*api密钥/i,
                /sk-your-real-.*-key-here/i,
                /sk-test-demo-key/i,
                /test-api-key-demo/i,
                /your-real-.*-key-here/i,
                /demo/i,
                /example/i,
                /placeholder/i,
                /占位符/i,
                /请输入/i
            ];

            const isPlaceholder = placeholderPatterns.some(pattern => pattern.test(data.apiKey));
            if (isPlaceholder) {
                showAlert('error', '请输入真实的API密钥，不能使用占位符或示例文本');
                return;
            }

            if (currentTab === 'custom' && (!data.name || !data.baseUrl)) {
                showAlert('error', '请填写完整的服务商信息');
                return;
            }

            showLoading(true);
            hideAllAlerts();

            try {
                const response = await fetch('/validate-provider', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                });

                const result = await response.json();

                if (result.success) {
                    // 验证成功，保存配置
                    const saveResponse = await fetch('/save-config', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            ...data,
                            models: result.models || []
                        })
                    });

                    const saveResult = await saveResponse.json();

                    if (saveResult.success) {
                        showAlert('success', '配置保存成功！您可以继续配置其他服务商，或手动关闭此窗口。');
                    } else {
                        showAlert('error', '保存配置失败: ' + saveResult.error);
                    }
                } else {
                    showAlert('error', 'API密钥验证失败: ' + result.error);
                }
            } catch (error) {
                showAlert('error', '网络错误: ' + error.message);
            } finally {
                showLoading(false);
            }
        }

  
        // 显示服务器关闭后的成功消息
        function showServerShutdownMessage() {
            // 隐藏错误提示
            const existingAlert = document.querySelector('.alert');
            if (existingAlert) {
                existingAlert.style.display = 'none';
            }

            // 创建成功消息容器
            const successContainer = document.createElement('div');
            successContainer.className = 'alert alert-success';
            successContainer.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                max-width: 500px;
                z-index: 1000;
                background: linear-gradient(135deg, #28a745, #20c997);
                color: white;
                padding: 20px;
                border-radius: 10px;
                box-shadow: 0 4px 20px rgba(40, 167, 69, 0.3);
            `;

            successContainer.innerHTML = `
                <h4 style="margin: 0 0 10px 0; font-size: 18px;">🎉 配置完成！</h4>
                <p style="margin: 0 0 15px 0; line-height: 1.5;">Web配置服务器已关闭，您的配置已保存。</p>
                <div style="background: rgba(255,255,255,0.1); padding: 15px; border-radius: 8px; margin: 15px 0;">
                    <p style="margin: 0 0 10px 0; font-weight: bold;">接下来您可以：</p>
                    <ul style="margin: 0; padding-left: 20px;">
                        <li style="margin-bottom: 8px;">🚀 <strong>运行测试</strong>：执行 <code style="background: rgba(0,0,0,0.2); padding: 2px 6px; border-radius: 3px;">npm test</code> 开始单元测试</li>
                        <li style="margin-bottom: 8px;">🔌 <strong>使用MCP服务</strong>：在支持MCP的客户端中配置Vision Analyzer</li>
                        <li style="margin-bottom: 8px;">⚙️ <strong>修改配置</strong>：运行 <code style="background: rgba(0,0,0,0.2); padding: 2px 6px; border-radius: 3px;">npm run setup</code> 重新配置</li>
                    </ul>
                </div>
                <p style="margin: 0; font-size: 14px; opacity: 0.9;">
                    <small>💡 此页面可以关闭，配置已保存在 .env 文件中</small>
                </p>
                <button onclick="this.parentElement.remove()" style="
                    margin-top: 15px;
                    background: rgba(255,255,255,0.2);
                    border: 1px solid rgba(255,255,255,0.3);
                    color: white;
                    padding: 8px 16px;
                    border-radius: 5px;
                    cursor: pointer;
                    font-size: 14px;
                ">知道了</button>
            `;

            document.body.appendChild(successContainer);

            // 10秒后自动隐藏提示
            setTimeout(() => {
                if (successContainer.parentElement) {
                    successContainer.remove();
                }
            }, 15000);

            // 禁用所有表单输入和按钮
            disableAllInteractions();
        }

        // 禁用所有交互元素
        function disableAllInteractions() {
            // 禁用所有输入框
            document.querySelectorAll('input, select, button').forEach(element => {
                element.disabled = true;
                element.style.opacity = '0.6';
                element.style.cursor = 'not-allowed';
            });

            // 添加页面标题提示
            const titleElement = document.querySelector('h1');
            if (titleElement) {
                titleElement.innerHTML = '✅ Vision Analyzer - 配置已完成 (服务器已关闭)';
                titleElement.style.color = '#28a745';
            }

            // 在页面顶部添加横幅提示
            const banner = document.createElement('div');
            banner.style.cssText = `
                background: linear-gradient(90deg, #28a745, #20c997);
                color: white;
                text-align: center;
                padding: 15px;
                font-weight: bold;
                position: sticky;
                top: 0;
                z-index: 100;
                box-shadow: 0 2px 10px rgba(40, 167, 69, 0.3);
            `;
            banner.innerHTML = '🎉 配置完成！Web服务器已关闭 - 您现在可以开始使用 Vision Analyzer 了';
            document.body.insertBefore(banner, document.body.firstChild);
        }

        // 页面加载完成后显示信息提示
        document.addEventListener('DOMContentLoaded', function() {
            showAlert('info');
        });
    </script>
</body>
</html>